package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdminService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.AdLoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.admin.AdUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Lijx
 * @Date 2024-07-30 21:36
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdUserMapper adUserMapper;

    /**
     * 平台管理用户登录
     * @param adLoginDto
     * @return
     */
    @Override
    public ResponseResult login(AdLoginDto adLoginDto) {
        if (adLoginDto == null || adLoginDto.getName() == null || adLoginDto.getPassword() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询登录用户信息是否存在
        AdUser adUser = adUserMapper.selectOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, adLoginDto.getName()));
        if (adUser == null) {
            throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //1. 先将前端传递的明文加盐，加盐后再加密，得到密文
        String pwdInput = MD5Utils.encode(adLoginDto.getPassword() + adUser.getSalt());
        //判断密码是否正确
        if (!pwdInput.equals(adUser.getPassword())) {
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //2. 校验当前用户状态
        if (adUser.getStatus() != 9){ //账号状态正常
            throw new CustomException(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }

        //3. 基于当前用户id生成token令牌
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));

        //4. 将当前用户信息和token令牌都返回即可
        Map<String,Object> resData = new HashMap<>();
        resData.put("token",token);
        adUser.setSalt("");
        adUser.setPassword("");
        resData.put("user",adUser);

        return ResponseResult.okResult(resData);
    }
}
